//
//  MessageSender.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/9/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation

class MessageSender{
    var socketClient:UwantSocketClient?
    var encoder:UwantJsonEncoder = UwantJsonEncoder()
    private var byteEncoder:GoEasyMessageEncoder=GoEasyMessageEncoder()
    private var maxRetries:UInt32 = 3
    
    init(socketClient: UwantSocketClient){
        self.socketClient = socketClient
    }
    func sendPing(){
        let pingSeconds = NSDate.timeIntervalSinceReferenceDate()
        let pingSecondsStr:String=String(pingSeconds)
        let content:[UInt8]=Array(pingSecondsStr.utf8)
        let pingMsg = Message(type: "PING", content: content)
        send(pingMsg)
    }
    
    func send(msg: [UInt8]){
        let message = Message(type: "MESSAGE", content: msg)
        send(message)
    }
    
    func send(clientMessage: ClientMessage){
        let bytes:[UInt8]=byteEncoder.encode(clientMessage)
        self.send(bytes)
    }
    
    private func send(mesage: Message){
        let encodedMsg:NSData = encoder.encode(mesage)
        socketClient!.socket?.writeData(encodedMsg, withTimeout: -1, tag: 0)
    }
}